package com.heima.wemedia.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    private static final List<String> IMAGE_TYPE_LIST = Arrays.asList("png","bmp","gif","jpeg","jpg");
    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) {
        //1. 判断文件的合法性
        //1.1 文件不能为空
        if(file.isEmpty() || file.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.2 文件必须为图片类型
        try {
            String type = FileTypeUtil.getType(file.getInputStream());
            if(!IMAGE_TYPE_LIST.contains(type)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"不是图片");
            }
            //2. 生成唯一文件名，前缀+后缀
            String filePrefixName = IdUtil.fastSimpleUUID();//文件前缀
            String filePostfixName = filePrefixName+"."+type;//文件后缀
            String fileName = filePrefixName+filePostfixName;

            //3. 文件上传到MinIO
            String url = fileStorageService.uploadImgFile(null, fileName, file.getInputStream());

                //4. 保存素材
                WmMaterial wmMaterial = new WmMaterial();
                wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
                wmMaterial.setUrl(url);
                wmMaterial.setType((short) 0);
                wmMaterial.setIsCollection((short) 0);
                wmMaterial.setCreatedTime(new Date());
                this.save(wmMaterial);
                //5. 返回结果
                return ResponseResult.okResult(url);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"上传失败");
        }
    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1. 设置分页参数的默认值
        dto.checkParam();

        //2. 查询素材列表
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        this.lambdaQuery()
                .eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId())
                .eq(dto.getIsCollection()>0,WmMaterial::getIsCollection,dto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime)
                .page(page);

        //3. 返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());

        return pageResponseResult;

    }

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
        //1. 判断参数的合法性
        if(id==null || id<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 判断数据是否存在
        Integer count = this.lambdaQuery().eq(WmMaterial::getId, id).count();
        if(count<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3. 判断素材图片是否被引用
        Integer countRelation = wmNewsMaterialService.lambdaQuery().eq(WmNewsMaterial::getMaterialId, id).count();
        if(countRelation>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"素材已被引用无法删除");
        }

        //4. 删除minio中的素材
        WmMaterial wmMaterial = this.getById(id);
        fileStorageService.delete(wmMaterial.getUrl());

        //5. 删除素材库数据
        this.removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        //1. 判断参数的合法性
        if(id == null || id<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 判断数据是否存在
        Integer count = this.lambdaQuery().eq(WmMaterial::getId, id).count();
        if(count<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3. 执行更新
        this.lambdaUpdate()
                .eq(WmMaterial::getId,id)
                .set(WmMaterial::getIsCollection, 0)
                .update();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        //1. 判断参数的合法性
        if(id == null || id<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 判断数据是否存在
        Integer count = this.lambdaQuery().eq(WmMaterial::getId, id).count();
        if(count<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3. 执行更新
        this.lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection, 1).update();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
